import { onMounted, onUnmounted, reactive, toRefs } from "vue";

export default function useScroll() {
    const state = reactive({
        scrollTop: 0,
        scrollBottom: 0,
        bodyHeight: 0,
    });

    const onScroll = (e) => {
        state.scrollTop = document.documentElement.scrollTop;
        state.scrollBottom =
            document.body.clientHeight - state.scrollTop - window.innerHeight;
        state.bodyHeight = document.body.clientHeight;
    };

    let timer = null;
    const toTop = (millis = 1000) => {
        yScrollTo(0, millis);
    };

    const yScrollTo = (y, millis = 1000) => {
        if (!timer) {
            const offset = document.documentElement.scrollTop - y;
            const frameOffset = Math.abs(offset / (millis / 40));

            timer = setInterval(() => {
                if (
                    offset > 0 &&
                    document.documentElement.scrollTop - y > frameOffset
                ) {
                    document.documentElement.scrollTop -= frameOffset;
                } else if (
                    offset < 0 &&
                    y - document.documentElement.scrollTop > frameOffset
                ) {
                    document.documentElement.scrollTop += frameOffset;
                } else {
                    document.documentElement.scrollTop = y;
                    clearInterval(timer);
                    timer = null;
                }
            }, 40);
        }
    };

    onMounted(() => {
        window.addEventListener("scroll", onScroll);
    });

    onUnmounted(() => window.removeEventListener("scroll", onScroll));

    // 对外返回一堆ref
    return { ...toRefs(state), toTop, yScrollTo };
}
